import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Text, ScrollView } from '@tarojs/components'
import { AtDivider, AtSearchBar, AtIcon } from 'taro-ui'
import { observer, inject } from '@tarojs/mobx'
import ProductStore from '../../stores/productStore'
import Stores from '../../stores/storeIdentifier'
import './list.scss'
import { ProductListDto } from '../../services/product/dto/productListDto'
import { PagedList } from '../../services/dto/pagedList'
import { SearchLogDto } from '../../services/searchLog/dto/searchLogDto'
import SearchLogStore from '../../stores/searchLogStore'
import ModuleTypeIds from '../../services/dto/moduleTypeIds'

export interface IListProps {
  productStore: ProductStore,
  searchLogStore: SearchLogStore
}

@inject(Stores.ProductStore, Stores.SearchLogStore)
@observer
class List extends Component<IListProps> {
  config: Config = {
    navigationBarTitleText: '商品搜索'
  };

  state = {
    needload: true,
    sort: true,
    keywords: '',
    skipCount: 0,
    sorting: 'id desc',
    maxResultCount: 10,
    searchStatus: true
  }
  logs: SearchLogDto[]
  products: PagedList<ProductListDto>

  constructor(props) {
    super(props)
  }

  async componentWillMount() {
    await this.getProducts()
    await this.getMySearchLogs()
  }

  getMySearchLogs = async () => {
    await this.props.searchLogStore.getMySearchLogs({ moduleTypeId: ModuleTypeIds.Product });
    this.logs = this.props.searchLogStore.logs;
    this.setState({})
  }

  onChange(value) {
    this.setState({
      keywords: value
    })
  }

  onFocus() {
    this.setState({
      searchStatus: true
    })
  }

  onActionClick() {
    this.setState({
      searchStatus: false
    })
    this.products.currentPage = 0;
    this.products.skipCount = 0;
    this.products.totalCount = 0;
    this.products.totalPages = 0;
    this.products.items = [];
    this.setState({
      needload: true,
      keywords: this.state.keywords,
      skipCount: 0,
    }, async () => {
      await this.getProducts()
      await this.createLogs()
      await this.getMySearchLogs()
    })
  }

  createLogs = async () => {
    await this.props.searchLogStore.createLogs({ keywords: this.state.keywords, moduleTypeId: ModuleTypeIds.Product })
  }

  getProducts = async () => {

    await this.props.productStore.getProductPagedListAsync({
      sorting: this.state.sorting,
      maxResultCount: this.state.maxResultCount,
      skipCount: this.state.skipCount,
      keyWords: this.state.keywords
    });

    const { products } = this.props.productStore;
    let needload = true;
    if (this.products) {
      this.products.currentPage = products.currentPage;
      this.products.skipCount = products.skipCount;
      this.products.totalCount = products.totalCount;
      this.products.totalPages = products.totalPages;
      this.products.maxResultCount = products.maxResultCount;
      this.products.items = [...this.products.items, ...products.items]
    } else {
      this.products = products;
    }
    needload = !(this.products.items.length >= this.products.totalCount);
    this.setState({ needload: needload });
  }

  async selectLogs(keywords) {
    this.products.currentPage = 0;
    this.products.skipCount = 0;
    this.products.totalCount = 0;
    this.products.totalPages = 0;
    this.products.maxResultCount = 0;
    this.products.items = [];

    this.setState({ searchStatus: false, keywords: keywords }, async () => {
      await this.getProducts()
    })
  }

  async deleteHis() {
    await this.props.searchLogStore.deleteAll(ModuleTypeIds.Product)
    this.logs = []
    this.setState({})
  }

  gotoDetail = (e) => {
    Taro.navigateTo({
      url: `/pages/product/index?id=${e.currentTarget.dataset.id}`,
    })
  }
  onScrollToLower = async () => {
    this.setState({ skipCount: this.state.skipCount + this.state.maxResultCount }, async () => {
      if (this.state.needload)
        await this.getProducts();
    })
  }

  orderBy = (e) => {
    let sorting
    if (e.currentTarget.dataset.type === '1') {
      if (this.state.sorting == 'id desc') {
        return
      }
      sorting = 'id desc';
    } else {
      sorting = 'price ';
      sorting = this.state.sort ? sorting + 'asc' : sorting + 'desc';
    }
    this.products.currentPage = 0;
    this.products.skipCount = 0;
    this.products.totalCount = 0;
    this.products.totalPages = 0;
    this.products.maxResultCount = 0;
    this.products.items = [];
    this.setState({
      needload: true,
      skipCount: 0,
      sorting: sorting,
      sort: !this.state.sort,
    }, async () => {
      await this.getProducts();
    })
  }

  render() {
    return (
      <View className='pro-list-wrap'>
        <AtSearchBar
          focus
          showActionButton
          value={this.state.keywords}
          onChange={this.onChange.bind(this)}
          onActionClick={this.onActionClick.bind(this)}
          onFocus={this.onFocus.bind(this)}
        />
        {
          this.state.searchStatus && (
            <View className='search-log'>
              {this.logs && this.logs.length && <View className='search-header'>历史记录<AtIcon value='trash' size='20' color='#666666' onClick={this.deleteHis} /></View>}
              <View className='search-body'>
                {
                  this.logs.map((item) => (
                    <Text onClick={this.selectLogs.bind(this, item.keywords)}>{item.keywords}</Text>
                  ))
                }
              </View>
            </View>
          )
        }
        {
          !this.state.searchStatus && (
            <View className='proResult'>
              <View className='pro-filter ratina-bd bd-b'>
                <View className='filter-item' data-type='1' onClick={this.orderBy}>综合</View>
                {this.state.sort && <View className='filter-item' data-type='2' onClick={this.orderBy}>价格↓</View>}
                {!this.state.sort && <View className='filter-item' data-type='2' onClick={this.orderBy}>价格↑</View>}
              </View>
              <ScrollView
                className='scrollview'
                scrollY
                scrollWithAnimation
                onScrollToLower={this.onScrollToLower}
              >
                <View className='pro-list'>
                  {
                    this.products.items.length > 0 ? (
                      this.products.items.map((item, index) => (
                        <View className='pro-item' key={index} onClick={this.gotoDetail} data-id={item.id}>
                          <Image className='pro-img' src={item.featuredImageUrl} />
                          <View className='pro-title'>{item.name}</View>
                          <View className='pro-price'>
                            <Text className='now-price'>￥{item.price}</Text>
                          </View>
                        </View>
                      ))
                    )
                      : (
                        <View className='no-msg'>
                          <AtDivider content='暂无数据' />
                        </View>
                      )
                  }


                </View>
              </ScrollView>
            </View>
          )
        }

      </View>
    )
  }
}

export default List
